package com.lin.linchatgpt.ws;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.lin.linchatgpt.entity.dto.ResponseMidjourneyDTO;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/7/9 8:34
 * @Description
 */
@Slf4j
@Component
@ServerEndpoint("/lin_chat/ws/generate_image/notification/{userId}")
public class GenerateImageMessage {
    private static final Map<String, GenerateImageMessage> onlineUsers = new ConcurrentHashMap<>();

    private String userId;
    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = session.getRequestParameterMap().get("userId").get(0);
        onlineUsers.put(userId, this);
        log.info("有新的连接加入，用户:{}！当前在线人数为{}", userId, onlineUsers.size());
    }

    @OnClose
    public void onClose() {
        onlineUsers.remove(this.userId);
        log.info("有连接关闭！当前在线人数为{}", onlineUsers.size());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("发生连接错误，用户:{},原因:{}", this.userId, throwable.getMessage());
        throwable.printStackTrace();
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        session.getAsyncRemote().sendText(message);
    }

    public void sendOneMessage(String userId, ResponseMidjourneyDTO message) {
        GenerateImageMessage generateImageMessage = onlineUsers.get(userId);
        if (ObjectUtil.isNotNull(generateImageMessage)) {
            Session session = generateImageMessage.session;
            if (session.isOpen()) {
                log.info("发送消息到用户{}，内容为:{}", userId, message);
                session.getAsyncRemote().sendText(JSONObject.toJSONString(message));
            }
        }
    }


}

